import json
from chats.models import ChatData, GroupData, GroupUser, GroupMessage
from django.db.models import Q
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse,HttpResponseForbidden
# Create your views here.
from users.models import User, Friend
from utails.pushfile import request_to



class GroupChatImg(View):
    '''群聊聊天图片'''
    def post(self, request):
        userid = request.POST.get('userid', None)
        group = request.POST.get('friend', None)
        file = request.FILES.get('file')
        if userid is None or group is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
            group = GroupData.objects.get(id=group)
        except:
            return HttpResponseForbidden('403')
        # 上传图片
        res = request_to(file,'',0,0)
        # 保存
        try:
            GroupMessage.objects.create(
                user=user,
                group=group,
                types=1,
                chat_data=res,
                status=0
            )
        except:
            return JsonResponse({'code':'400'})
        # 同步信息
        try:
            group.new_data = '(图片)',
            group.save()
        except:
            print('数据同步失败')
        # 记录各用户未读
        user_group = group.group_g.all()
        for i in user_group:
            i.tip += 1
            i.save()

        return JsonResponse(res, safe=False)

class GroupView(View):
    '''群聊聊天页面'''
    def get(self, request):
        usera = request.GET.get('usera')
        userb = request.GET.get('userb') # 群聊id
        nowpage = request.GET.get('nowpage')
        maxpage = request.GET.get('maxpage')

        if not all([usera, userb, nowpage, maxpage]):
            return HttpResponseForbidden('缺少必传参数')
        try:
            usera = User.objects.get(id=usera)
            group = GroupData.objects.get(id=userb)
        except:
            return HttpResponseForbidden('400')

        # 获取一对一聊天数据
        chat_data = GroupMessage.objects.filter(group=group).order_by('-id')

        # 分页操作
        maxpage = len(chat_data) // 10 + 1
        nowpage = int(nowpage)
        if maxpage != 1:
            if nowpage == maxpage:
                chat_data = chat_data[(nowpage - 1) * 10:len(chat_data)][::-1]
            else:
                chat_data = chat_data[(nowpage - 1) * 10:nowpage * 10][::-1]
        else:
            if len(chat_data) == 0:
                return JsonResponse([], safe=False)
            chat_data = chat_data[::-1]

        # 序列化
        content = {'data': []}
        for i in chat_data:
            if i.user == usera:
                user = usera
                tip = 1  # 自己的信息
            else:
                user = i.user
                # 设置为已读
                i.status = 1
                i.save()
                tip = 0  # 群友的信息
            content['data'].append({
                'id': i.id,
                'uid':i.user.id,
                'userimg': user.default_image,
                'message': i.chat_data,
                'types': i.types,
                'time': i.create_time,
                'tip': tip
            })
        content['maxpage'] = maxpage
        content['group'] = {
            'groupid':group.id,
            'groupname':group.groupname,
            'group_img':group.group_img
        }

        return JsonResponse(content, safe=False)

    def post(self, request):
        jsondict = json.loads(request.body.decode())
        chat_a = jsondict.get('usera')
        group = jsondict.get('userb')
        chat_data = jsondict.get('message')
        tip = jsondict.get('tip')
        types = jsondict.get('types')

        if not all([group, chat_a, chat_data, tip]):
            return HttpResponseForbidden('403')

        try:
            user = User.objects.get(id=chat_a)
            group = GroupData.objects.get(id=group)
        except:
            return HttpResponseForbidden('没有关注')

        # 文本数据
        try:
            GroupMessage.objects.create(
                user=user,
                group=group,
                chat_data=chat_data,
                types=types,
                status=0
            )
            group.new_data = chat_data
            group.save()
        except:
            return JsonResponse({'code': '400'})
        # 记录各用户未读
        user_group = group.group_g.all()
        for i in user_group:
            i.tip += 1
            i.save()

        return JsonResponse({'code': '200'})

    def delete(self, request):
        # 清空最新信息提示
        jsondict = json.loads(request.body.decode())
        chat_a = jsondict.get('usera')
        group = jsondict.get('userb')
        if not all([chat_a, group]):
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=chat_a)
            group = GroupData.objects.get(id=group)
        except:
            return HttpResponseForbidden('400')
        try:
            usergroup = group.group_g.get(user=user)
            usergroup.tip = 0
            usergroup.save()
        except:
            return JsonResponse({'code':'400'})
        return JsonResponse({'code': '200'})


class getAddFriend(View):
    '''查找不在群内的好友'''
    def get(self, request):
        userid = request.GET.get('userid', None)
        groupname = request.GET.get('groupname', None)
        if userid is None or groupname is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
            group = GroupData.objects.get(groupname=groupname)
        except:
            return HttpResponseForbidden('400')
        # 获取群成员
        user_g = [i.user for i in group.group_g.all()]
        # 获取好友
        friends = Friend.objects.exclude(user_a__in=user_g, user_b__in=user_g).filter(Q(user_a=user)|Q(user_b=user), status=1)
        content = []
        for i in friends:
            f_user = i.user_b if i.user_a==user else i.user_a
            content.append({
                'id': f_user.id,
                'selected':'false',
                'name':f_user.username,
                'userImg':f_user.default_image
            })
        return JsonResponse(content, safe=False)



class GroupDetail(View):
    '''群详情页'''
    def get(self, request):
        userid = request.GET.get('userid', None)
        groupname = request.GET.get('groupname', None)
        # 在群内
        if userid is None or groupname is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
            group = GroupData.objects.get(groupname=groupname)

        except:
            return HttpResponseForbidden('400')
        try:
            # 判断是否在群内 获取群内个人信息
            user_group = user.user_g.get(group=group)
        except:
            # 不在群内
            user_group = False

        # 获取好友
        user_groups = group.group_g.exclude(user=user)
        content = {'users': [],'group': {},'user_gruop': {}}
        #  成员信息
        for i in user_groups:
            user_g = i.user
            content['users'].append({
                'id': user_g.id,
                'name': user_g.username,
                'userImg': user_g.default_image
            })
        #  群聊信息
        content['group'] = {
            'groupname':group.groupname,
            'notice':group.notice,
            'group_img':group.group_img,
            'groupdate':group.create_time
        }
        # 用户群内信息
        if user_group:
            content['user_gruop']= {
                'inner_name':user_group.inner_name,
                'tip':user_group.tip,
                'status':user_group.status,
                'ismaster': 1 if group.master==user else 0
            }
        else:
            content['user_gruop'] = 0

        return JsonResponse(content, safe=False)

    def post(self,request):
        jsondict = json.loads(request.body.decode())
        userid = jsondict.get('userid')
        groupname = jsondict.get('groupname')
        types = jsondict.get('types')
        datas = jsondict.get('datas')
        if not all([userid, types, groupname]):
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
            # group = user.master.get(goupname=goupname)
            group = GroupData.objects.get(groupname=groupname)
        except:
            return HttpResponseForbidden('403')

        try:
           if types == '群名称':
               group.groupname = datas
           elif types == '群公告':
               group.notice = datas
           else:
               return HttpResponseForbidden('403')
           group.save()
        except:
            return JsonResponse({'code':'400'})

        return JsonResponse({'code':'200'})

    def put(self, request):
        '''拉人进群  加入群聊'''
        jsondict = json.loads(request.body.decode())
        userid = jsondict.get('userid')
        groupname = jsondict.get('groupname')
        add_users = jsondict.get('add_users')

        if not all([userid, groupname, add_users]):
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
            group = GroupData.objects.get(groupname=groupname)
        except:
            return HttpResponseForbidden('403')
        # 添加成员
        users = User.objects.filter(id__in=add_users)
        try:
            for u in users:
                GroupUser.objects.create(user=u, group=group)
        except:
            return JsonResponse({'code': '400'})
        return JsonResponse({'code': '200'})

    def delete(self, request):
        '''踢人 退出群聊'''
        jsondict = json.loads(request.body.decode())
        userid = jsondict.get('userid')
        groupname = jsondict.get('groupname')
        del_user = jsondict.get('del_user')
        if not all([userid, groupname, del_user]):
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
            del_user = User.objects.get(id=del_user)
            group = GroupData.objects.get(groupname=groupname)
        except:
            return HttpResponseForbidden('403')
        # 删除
        try:
            user_del = GroupUser.objects.get(group=group, user=del_user)
            user_del.delete()
        except:
            return JsonResponse({'code':'400'})

        return JsonResponse({'code':'200'})


class GroupImg(View):
    '''上传群头像'''
    def post(self, request):
        userid = request.POST.get('userid', None)
        groupname = request.POST.get('groupname')
        file = request.FILES.get('file')
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('403')
        try:
            group = user.master.get(groupname=groupname)
        except:
            return HttpResponseForbidden({'code':'400'})
        # 上传图片
        ord_img = group.group_img
        res = request_to(file, '', 0, ord_img)
        # 保存
        try:
            group.group_img = res
            group.save()
        except:
            return JsonResponse({'code': '400'})
        return JsonResponse({'code': '200'})

class GroupBuildView(View):
    '''建群'''
    def get(self, request):
        userid = request.GET.get('userid', None)
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('400')
        # 获取好友
        friends = Friend.objects.filter(Q(user_a=user) | Q(user_b=user), status=1)
        if len(friends) == 0:
            return JsonResponse([], safe=False)
        content = []
        for i in friends:
            f_user = i.user_b if i.user_a==user else i.user_a
            content.append({
                'id': f_user.id,
                'selected':'false',
                'name':f_user.username,
                'userImg':f_user.default_image
            })
        return JsonResponse(content, safe=False)
    def post(self, request):
        jsondict = json.loads(request.body.decode())
        userid = jsondict.get('userid')
        groupname = jsondict.get('groupname')
        users = jsondict.get('users')

        if not all([users, groupname, users]):
            return HttpResponseForbidden('400')

        try:
            master = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('403')
        # 创建群聊
        try:
            group = GroupData.objects.create(
                master=master,
                groupname=groupname
            )
        except:
            return JsonResponse({'code':'400'})
        # 拉取成员
        users = User.objects.filter(id__in=users)
        try:
            for u in users:
                GroupUser.objects.create(user=u,group=group)
        except:
            return JsonResponse({'code':'400'})

        return JsonResponse({'code':'200'})



class ChatPushImg(View):
    '''聊天图片数据'''
    def post(self, request):
        userid = request.POST.get('userid', None)
        friend = request.POST.get('friend', None)
        file = request.FILES.get('file')
        if userid is None or friend is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
            friend = User.objects.get(id=friend)
        except:
            return HttpResponseForbidden('403')
        # 上传图片
        res = request_to(file,'',0,0)
        # 保存
        try:
            ChatData.objects.create(
                chat_a=user,
                chat_bir=friend,
                types=1,
                chat_data=res,
                status=0
            )
        except:
            return JsonResponse({'code':'400'})
        # 同步信息
        try:
            friend = Friend.objects.get(user_a=user, user_b=friend)
            friend.mew_data = '(图片)'
            friend.save()
        except:
            print('数据同步失败')


        return JsonResponse(res, safe=False)



class ChatrommDate(View):
    '''一对一聊天'''
    def get(self, request):
        usera = request.GET.get('usera')
        userb = request.GET.get('userb')
        nowpage = request.GET.get('nowpage')
        maxpage = request.GET.get('maxpage')

        if not all([usera, userb, nowpage, maxpage]):
            return HttpResponseForbidden('缺少必传参数')
        try:
            usera = User.objects.get(id=usera)
            userb = User.objects.get(id=userb)
        except:
            return HttpResponseForbidden('400')

        # 获取一对一聊天数据
        chat_data = ChatData.objects.filter(Q(chat_a=usera,chat_bir=userb)|Q(chat_a=userb,chat_bir=usera)).order_by('-id')

        # 分页操作
        maxpage = len(chat_data)//10 + 1
        nowpage = int(nowpage)
        if maxpage!=1:
            if nowpage == maxpage:
                chat_data = chat_data[(nowpage-1)*10:len(chat_data)][::-1]
            else:
                chat_data = chat_data[(nowpage-1)*10:nowpage*10][::-1]
        else:
            if len(chat_data)==0:
                return JsonResponse([],safe=False)
            chat_data = chat_data[::-1]

        # 序列化
        content = {'data':[]}
        for i in chat_data:
            if i.chat_a==usera:
                user = usera
                tip = 1
            else:
                user = userb
                # 设置为已读
                i.status = 1
                i.save()
                tip = 0
            content['data'].append({
                'id':i.id,
                'uid': user.id,
                'userimg':user.default_image,
                'message':i.chat_data,
                'types':i.types,
                'time':i.create_time,
                'tip':tip
            })
        content['maxpage'] = maxpage
        content['friend'] = {
            'fname':userb.username,
            'fid':userb.id
        }

        return JsonResponse(content, safe=False)

    def post(self, request):
        jsondict = json.loads(request.body.decode())
        chat_a = jsondict.get('usera')
        chat_b = jsondict.get('userb')
        chat_data = jsondict.get('message')
        tip = jsondict.get('tip')
        types = jsondict.get('types')

        if not all([chat_b, chat_a, chat_data, tip]):
            return HttpResponseForbidden('403')

        try:
            chat_a = User.objects.get(id=chat_a)
            chat_b = User.objects.get(id=chat_b)
            friend = Friend.objects.get(Q(user_a=chat_a, user_b=chat_b)|Q(user_a=chat_b, user_b=chat_a))
        except:
            return HttpResponseForbidden('没有关注')

        # 文本数据
        try:
            ChatData.objects.create(
                chat_a=chat_a,
                chat_bir=chat_b,
                chat_data=chat_data,
                types=types,
                status=0
            )
            friend.mew_data = chat_data
            friend.save()
        except :
            return JsonResponse({'code':'400'})

        return JsonResponse({'code':'200'})
    def delete(self, request):
        # 清空最新信息提示
        jsondict = json.loads(request.body.decode())
        chat_a = jsondict.get('usera')
        chat_b = jsondict.get('userb')
        if not all([chat_a, chat_b]):
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=chat_a)
            friend = User.objects.get(id=chat_b)
        except:
            return HttpResponseForbidden('400')
        chats = ChatData.objects.filter(chat_a=friend, chat_bir=user, status=0)
        try:
            for i in chats:
                i.status = 1
                i.save()
        except:
            return JsonResponse({'code':'400'})
        return JsonResponse({'code':'200'})





